package com.zucai365.football.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.zucai365.football.bean.CurrentFootballTeamBean;
import com.zucai365.football.bean.FootballTeamBean;
import com.zucai365.football.bean.GameFireBean;
import com.zucai365.football.bean.LianSaiBean;
import com.zucai365.football.bean.LianSaiInfoBean;
import com.zucai365.football.bean.LianSaiYearBean;
import com.zucai365.football.bean.ShouFaBean;
import com.zucai365.football.bean.TeamDZBean;

public class ZuCaiUtils {
	
	//默认联赛年份
	public static Long CURRENT_LIANSAI_YEAR;
	
	//默认联赛
	public static Long CURRENT_LIANSAI;
	
	public static Long getCurrentLianSaiYear() {
		return ZuCaiUtils.CURRENT_LIANSAI_YEAR;
	}
	
	public static LianSaiBean getLianSaiById( Long id ) {
		for ( LianSaiBean liansai : Constant.ALL_LIANSAI_LIST ) {
			if ( liansai.getId().toString().equals( id.toString() )) {
				return liansai;
			}
		}
		return null;
	}
	
	public static LianSaiYearBean getLianSaiYearById( Long id ) {
		for ( LianSaiYearBean liansaiYear : Constant.ALL_LIANSAI_YEAR_LIST ) {
			if ( liansaiYear.getId().toString().equals( id.toString() )) {
				return liansaiYear;
			}
		}
		return null;
	}
	
	/**
	 * 得到每个国家比赛的当前轮次
	 * @param liansaiId
	 * @param liansaiYearId
	 * @return
	 */
	public static int getCurrentLunci( Long liansaiId,Long liansaiYearId ) {
		for ( LianSaiInfoBean lianSaiInfo : Constant.ALL_LIANSAI_INFO_LIST ) {
			if ( lianSaiInfo.getLianSai().getId()== liansaiId 
					&& lianSaiInfo.getLianSaiYear().getId() == liansaiYearId ) {
				return lianSaiInfo.getLunci();
			}
		}
		return -1;
	}
	
	/**
	 * 下载每个联赛的球队数据
	 */
	public static void dowloadTeamJs(List<LianSaiInfoBean> lianSaiInfoList) {
		for (LianSaiInfoBean lianSaiInfo : lianSaiInfoList) {
			ZuCaiUtils.dowloadTeamJs(lianSaiInfo);
		}
	}
	
	/**
	 * 下载每个联赛的球队数据
	 */
	public static void dowloadTeamJs( LianSaiInfoBean lianSaiInfo ) {
		
			String liansaiEnglish = lianSaiInfo.getLianSai().getEnglishName();
			String lianSaiYearName = lianSaiInfo.getLianSaiYear()
					.getLiansaiYear();
			String path = Constant.WAR_PATH + "teamInfo/" + liansaiEnglish+ "/";
			String bet007_url = lianSaiInfo.getUrlBet007();
			if( StringUtils.isBlank( bet007_url ) ){
				return;
			}
			File f = new File(path);
			if (!f.exists()) {
				f.mkdirs();
			}
			
			try {
				String urlContent = ZuCaiUtils.getUrlContent( bet007_url, "utf-8" );
				String jsPath = path + lianSaiYearName + ".js";
				
				FileOutputStream out = new FileOutputStream( jsPath );
				out.write( urlContent.getBytes( "utf-8" ) );
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
	}
	
	/**
	 * 下载每个球队的人员信息
	 */
	public static void dowloadTeamPlayerJS( List<CurrentFootballTeamBean> currentFootballTeamList ) {
		for ( CurrentFootballTeamBean currentFootballTeamBean : currentFootballTeamList ) {
			ZuCaiUtils.dowloadTeamPlayerJS( currentFootballTeamBean );
			
		}
	}
	
	
	/**
	 * 下载每个球队的人员信息
	 */
	public static void dowloadTeamPlayerJS( CurrentFootballTeamBean currentFootballTeamBean ) {
		
			String liansaiEnglish = currentFootballTeamBean.getLiansai().getEnglishName();
			String lianSaiYearName = currentFootballTeamBean.getLiansaiYear().getLiansaiYear();
			String path = Constant.WAR_PATH + "teamInfo/" + liansaiEnglish+ "/";
			
			String player_url = currentFootballTeamBean.getUrlPlayer();
			if( StringUtils.isBlank( player_url ) ){
				return;
			}
			File f = new File(path);
			if (!f.exists()) {
				f.mkdirs();
			}
			
			try {
				String urlContent = ZuCaiUtils.getUrlContent( player_url, "utf-8" );
				String jsPath = path + "player_" + currentFootballTeamBean.getFootballTeam().getFootballTeamName() + "_"+lianSaiYearName+".js";
				
				FileOutputStream out = new FileOutputStream( jsPath );
				out.write( urlContent.getBytes( "utf-8" ) );
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
					
	}
	
	
	//获取传入url的内容
	public static String getUrlContent(String url, String charset) throws Exception {

		URL urlmy = new URL(url);

		HttpURLConnection con = (HttpURLConnection) urlmy.openConnection();

		con.setFollowRedirects(true);

		con.setInstanceFollowRedirects(false);

		con.connect();

		BufferedReader br = new BufferedReader(new InputStreamReader(
				con.getInputStream(), charset));

		String s = "";

		StringBuffer sb = new StringBuffer("");
		while ((s = br.readLine()) != null) {
			sb.append(s + "\r\n");
		}

		return sb.toString();
	}
	
	public static String getTeamDZJson( LianSaiBean liansai, LianSaiYearBean liansaiYear , int lunci ){
		
		String path = Constant.WAR_PATH + "teamInfo/" + liansai.getEnglishName()+ "/";
		
		String jsPath = path + liansaiYear.getLiansaiYear() + ".js";
		
		File jsFile = new File( jsPath );
		FileInputStream stream = null;
		InputStreamReader reader = null;
		BufferedReader br = null;
		//球队对阵json字符串
		String teamDZJson = "";
		
		try {
			stream = new FileInputStream( jsFile );
			reader = new InputStreamReader( stream, "utf-8" );
			br = new BufferedReader( reader );		
			
			String s = "";
			while (( s = br.readLine()) != null ) {			
				if( s.startsWith( "jh[\"R_"+lunci+"\"]" )){
					teamDZJson = s.split( "=" )[1].trim() ;
					teamDZJson = teamDZJson.substring( 0, teamDZJson.length()-1 );
					break;
				}
			}				
			
		} catch ( Exception e) {
			throw new RuntimeException( e.getCause() );
		}finally{
			try {
				stream.close();
				reader.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return teamDZJson;
	}
	
	public static List<ShouFaBean> parseShouFa( String shoufaMsg , TeamDZBean teamDZ , FootballTeamBean footballTeam ){
		
		
		Document shoufaDoc = Jsoup.parse( shoufaMsg );
		Elements tr = shoufaDoc.getElementsByTag( "tr" );
		
		Document adoc = Jsoup.parse( tr.toString() );
		Elements a = adoc.getElementsByTag( "a" );
		
		List<ShouFaBean> shuofaList = new ArrayList<ShouFaBean>();
		
		for( int j=0;j<a.size();j++ ){
			
			ShouFaBean shuofa = new ShouFaBean();
			
			Element element = a.get(j);
			String playerId = element.attr( "href" ).split( "\\?" )[1].split( "&" )[0].split( "=" )[1];
			String[] text = element.html().split( "&nbsp;" );
			String jerseyNumber = text[0].trim();
			String personName = text[1].trim();
			if( StringUtils.isBlank( jerseyNumber ) ){
				continue;
			}
//			FootballPlayerService footballPlayerService = (FootballPlayerService) SpringBeanUtils.getBean( "footballPlayerService" );
//			FootballPlayerBean footballPlayer = footballPlayerService.getFootballPlayer(  playerId );
			
			shuofa.setPersonName(personName);
			shuofa.setPlayerId( playerId );
			shuofa.setFootballTeam( footballTeam );
			shuofa.setLiansaiId( teamDZ.getLiansai().getId() );
			shuofa.setLiansaiYearId( teamDZ.getLiansaiYear().getId() );
			shuofa.setLunci( teamDZ.getLunci() );
			shuofa.setTeamDz( teamDZ );
			shuofa.setJerseyNumber( Integer.parseInt( jerseyNumber) );
			if( j>10){
				shuofa.setShouFa( "替补" );
				shuofa.setPlayingSumTime( 0 );
			}else{
				shuofa.setShouFa( "主力" );
				shuofa.setPlayingSumTime( 90 );
			}
			shuofaList.add( shuofa );
		}
		
		return shuofaList;
	}
	
	public static List<GameFireBean> parseGameFire( String gameFireMsg , TeamDZBean teamDZ , FootballTeamBean zdTeam , FootballTeamBean kdTeam ){
		
		gameFireMsg = gameFireMsg.replace( "tr class=\"font12\"", "tr class=\"fontzucai\"");
		
		Document doc = Jsoup.parse( gameFireMsg );
		Elements tr = doc.getElementsByClass( "fontzucai" );
		
		//System.out.println( tr.toString() );
		
		List<GameFireBean> gameFireList = new ArrayList<GameFireBean>();
		
		for( int i=0;i<tr.size();i++ ){
			Element element = tr.get(i);
			
			String zdEvent = element.childNode(1).childNode(0).toString().trim().replace( "&nbsp;", "" );
			String zdEventContent = element.childNode(3).toString().trim() ;
			
			String kdEventContent = element.childNode(7).toString().trim() ;
			String kdEvent = element.childNode(9).childNode(0).toString().trim().replace( "&nbsp;", "" ) ;
			
			boolean isZd = true;
			
			//客队比赛事件
			if( zdEvent.equals( "" ) && !kdEvent.equals( "" ) ){
				
				String time = element.childNode(5).childNode(0).childNode(0).toString().trim() ;
				time=time.substring(0,time.length()-1 ).trim();
				
				isZd = false;
				parsePlayerMsg( kdEvent,kdEventContent,time,teamDZ,isZd ,gameFireList );
			}else if( kdEvent.equals( "" ) && !zdEvent.equals( "" ) ){ //主队比赛事件		
				
				String time = element.childNode(5).childNode(0).childNode(0).toString().trim() ;
				time=time.substring(0,time.length()-1 ).trim();
				
				isZd = true;
				parsePlayerMsg( zdEvent,zdEventContent,time,teamDZ,isZd ,gameFireList );
			}else{
				continue;//两者都为空，继续。
			}			
		}
		
		return gameFireList;
	}
	
	public static String[] getPlayer( String msg ){
		Document doc1 = Jsoup.parse( msg );
		Elements a = doc1.getElementsByTag( "a" );
		String playerId = a.get(0).attr( "href" ).split( "\\?" )[1].split( "&" )[0].split( "=" )[1];
		String playerName = a.get(0).text().trim();
		String[] player = { playerId, playerName };
		return player;
	}
	
	
	public static void parsePlayerMsg( String event , String eventContent , String time, TeamDZBean teamDZ , boolean isZd , List<GameFireBean> gameFireList ){
				
		/**
		 * zdEvent 或者  kdEvent 中的字符串有下列情况：
		 * 1.gif 进球
		 * 7.gif 点球
		 * 8.gif 乌龙球
		 * 3.gif 黄牌
		 * 2.gif 红牌
		 * 9.gif 两黄变红
		 * 11.gif 换人
		 */
		
		if( event.indexOf( "/11.gif" ) > -1 ){ //换人
			//<td class="font12">(19)<img src="../bf_img/4.gif" />(12)<img src="../bf_img/5.gif" /></td>
						
			Pattern p = Pattern.compile( "\\((\\d+)\\)" , Pattern.DOTALL );
			Matcher matcher = p.matcher( eventContent );
			int flag = 0;
			String eventMsg = "";
			while( matcher.find() ){
				String  jerseyNumber = matcher.group(1) ;
				
				GameFireBean gameFire = new GameFireBean();
				
				gameFire.setLiansaiId( teamDZ.getLiansai().getId() );
				gameFire.setLiansaiYearId( teamDZ.getLiansaiYear().getId() );
				gameFire.setLunci( teamDZ.getLunci() );
				gameFire.setTeamDz( teamDZ );
				gameFire.setPlayTime( teamDZ.getPlayTime() );
				if( isZd ){
					gameFire.setEventFootballTeam( teamDZ.getZd() );
					gameFire.setEventFootballTeamName( teamDZ.getZd().getFootballTeamName() );
					gameFire.setFootballTeam(  teamDZ.getZd() );
					gameFire.setEventStatus( "主场" );
				}else{
					gameFire.setEventFootballTeam(  teamDZ.getKd() );
					gameFire.setEventFootballTeamName( teamDZ.getKd().getFootballTeamName() );
					gameFire.setFootballTeam(  teamDZ.getKd() );
					gameFire.setEventStatus( "客场" );
				}
				if( flag == 0 ){
					gameFire.setEvent( "换入" );
					eventMsg += jerseyNumber + ",换入;";
				}else{
					gameFire.setEvent( "换出" );
					eventMsg += jerseyNumber + ",换出";
				}
				flag++;
				gameFire.setEventTime( Integer.parseInt( time  ) );
				gameFire.setJerseyNumber( Integer.parseInt( jerseyNumber ) );
				
				gameFireList.add( gameFire );
			}
			
			gameFireList.get( gameFireList.size()-1 ).setEventMsg( eventMsg );
			gameFireList.get( gameFireList.size()-2 ).setEventMsg( eventMsg );
			
		}else{
			
			GameFireBean gameFire = new GameFireBean();
			
			gameFire.setLiansaiId( teamDZ.getLiansai().getId() );
			gameFire.setLiansaiYearId( teamDZ.getLiansaiYear().getId() );
			gameFire.setLunci( teamDZ.getLunci() );
			gameFire.setTeamDz( teamDZ );
			gameFire.setPlayTime( teamDZ.getPlayTime() );
			
			if( isZd ){
				gameFire.setEventFootballTeam( teamDZ.getZd() );
				gameFire.setEventFootballTeamName( teamDZ.getZd().getFootballTeamName() );
				gameFire.setFootballTeam(  teamDZ.getZd() );
				gameFire.setEventStatus( "主场" );
			}else{
				gameFire.setEventFootballTeam(  teamDZ.getKd() );
				gameFire.setEventFootballTeamName( teamDZ.getKd().getFootballTeamName() );
				gameFire.setFootballTeam(  teamDZ.getKd() );
				gameFire.setEventStatus( "客场" );
			}
			
			String playerId ="";
			String playerName = "";
			
			if( event.indexOf( "/1.gif" ) > -1 ){
				//<td class="font12"><a href="http://info.bet007.com/aspx/player.aspx?playerid=1814&amp;teamid=24" target="_blank">兰帕德</a></td>
				String[] player = getPlayer( eventContent );
				playerId = player[0];
				playerName = player[1];
				gameFire.setEvent( "进球" );
				
			}else if( event.indexOf( "/7.gif" ) > -1 ){
				String[] player = getPlayer( eventContent );
				playerId = player[0];
				playerName = player[1];
				gameFire.setEvent( "点球" );
			}else if( event.indexOf( "/8.gif" ) > -1 ){//乌龙球
				String[] player = getPlayer( eventContent );
				playerId = player[0];
				playerName = player[1];
				gameFire.setEvent( "乌龙球" );
				
				//如果是主队，那进球的就是客队人员
				if( isZd ){
					gameFire.setFootballTeam( gameFire.getTeamDz().getKd() );
				}else{
					gameFire.setFootballTeam( gameFire.getTeamDz().getZd() );
				}
				
			}else if( event.indexOf( "/3.gif" ) > -1 ){
				String[] player = getPlayer( eventContent );
				playerId = player[0];
				playerName = player[1];
				gameFire.setEvent( "黄牌" );
			}else if( event.indexOf( "/2.gif" ) > -1 ){
				String[] player = getPlayer( eventContent );
				playerId = player[0];
				playerName = player[1];
				gameFire.setEvent( "红牌" );
			}else if( event.indexOf( "/9.gif" ) > -1 ){
				String[] player = getPlayer( eventContent );
				playerId = player[0];
				playerName = player[1];
				gameFire.setEvent( "两黄变红" );
			}
			
			gameFire.setPersonName( playerName );
			gameFire.setPlayerId( playerId );
			gameFire.setEventTime( Integer.parseInt( time  ) );

			gameFireList.add( gameFire );
		}
		
	}
}
